import { defineStore } from 'pinia'

//跳转判断
import {outerHref} from '@/composables/outerHref.js'

//请求接口
import {
	postUploadAlone,postLogisticAlive
} from "@/service/index.js"

//请求接口
import {
	postOrderStoreImage,postOrderLogistic,postOrderList
} from "@/service/pagesA/customer.js"

//请求接口
import {
	getDrivingParameters,getDrivingV1
} from "@/service/pagesA/logisticsMaps/logisticsMaps.js"


//创建用户小仓库
const useCustomerStore = defineStore('Customer',{
  state:()=>{
    return {
			onArriveTrue:true,//模拟导航开关
			isEmulaterTrue:false,//判断是否中途退出
			tabsList:[{name: '配送中'},{name: '已完成'}],
			tabCurrent:0,//tab选中下标值index
			listTrue:false,//列表数据刷新
			listBuData:[],//缓存数据
			listData:[],//列表数据		
			listStatusData:[],//状态列表缓存数据
			loadingTrue:false,
			faceImg:'',//门脸照
			modalShow:false,//定位模态框
			locationAddres:null,//定位信息
			scriptShow:false,//备注弹窗
			scriptShowId:0,//订单号
			scriptContent:'',//司机备注内容
			
			showOne:false,//确认收货弹窗
			confirmData:null,//确认收货弹窗数据
			
			loadingType:0,//列表刷新  2不刷新
			
			dateValue:Date.parse(new Date()),//日期
			customize:false,//判断是否首次进入列表
			groupIndex:0,//判断总共请求几次
			groupShijian:120,//间隔120秒
			waypointsBloot:false, //默认
    }
  },
	actions:{
		//获取经纬度
		addressFun(){
			this.listData=[];
			// #ifdef APP-PLUS
			let _this=this;
			uni.getLocation({
					type: 'gcj02',
					isHighAccuracy:true,
					success: function (res) {
						console.log(res,'坐标')
						_this.postOrderListFun(res.latitude,res.longitude);
					},
					fail: error => {
						
					}
			});	
			// #endif
			// #ifdef H5
			// this.postOrderListFun(29.62388,106.583256); //我家
			this.postOrderListFun(29.623894,106.583275); //公司1
			// #endif
		},
		
		//获取列表数据
		async postOrderListFun(lat,lng,done=0){
			await postOrderList({
				lat:lat,
				lng:lng,
				done,
				shipping_date:this.timestampToTime(this.dateValue),
				confirm:1
			})
			.then((res)=>{
				this.loadingType = 2;
				this.listData=res;
				this.listData.forEach((it)=>{
					it.logistic_address==null?it.logistic_address_models=0:it.logistic_address_models=1;
					let arrs=[];
					it.orders.forEach((iem)=>{
						if(iem.postscript){
							arrs.push({
								order_id:it.orders.length>1?iem.order_id:'',
								postscript:iem.postscript
							})
						}
					})
					it.postscriptListData=arrs;
					
					
					// #ifdef APP-PLUS
					//判断是否是送货中
					if(it.status==2){
						//如果直径大于800米改变状态待配送
						if(parseInt(this.space(lat,lng,it.lat,it.lng)*1000)>800){
							this.postOrderLogisticStatus(it.id,0);
						}
					}
					// #endif
				})
					
				//配送列表数据postscriptListData
				if(done==0){
					//无货判断
					let nums=0;
					res.forEach((as,iy)=>{if(as.weight!=-1)nums++;})
					
					this.tabsList[0].name='配送中(' +nums+'单)';
					this.listTrue=true; //不刷新列表数据开关
					this.listBuData=this.listData; //缓存起
					console.log(this.listData,'配送列表数据')
					// #ifdef H5
					if(this.listData.length>0){
						this.waypointsBloot=true;
						this.waypointsFun(lng,lat);
					}
					
					// #endif
					
					// #ifdef APP-PLUS
					if(this.listData.length>0){
						this.waypointsBloot=true;
						this.waypointsFun(lng,lat);
					}
					// #endif
				}
				
				
				// #ifdef APP-PLUS
				//打开app首次进入列表页
				this.customize=true;
				if(this.tabCurrent==0 && this.listData.length==0){
					this.postLogisticAliveFun(false,false);
				}
				// #endif
			})
		},
		
		//线路画线
		waypointsFun(longitude,latitude){
			let data=JSON.parse(JSON.stringify(this.listData));
			if(data.length<=16){ //途径小于16 单路线规划
				//起始点
				let origin=longitude+','+latitude;
				
				//终点
				let	itemData=data.pop();
				let destination=itemData.lng+','+itemData.lat;
				
				//沿途
				let waypoints=[];
				data.forEach((it)=>{
					waypoints.push(it.lng+','+it.lat)
				})
				this.getDrivingParametersFunOne(this.listData,origin,destination,waypoints.join(';'));
			}else{ //多路线规划
				this.groupIndex=0;
				let num=16; //数字
				let group=Math.floor(data.length/num);//线路条数
				let remainder=data.length%num; //余的条数
				let numNuber=group+(remainder>0?1:0); //请求几次
				for(var j=0;j<group;j++){
					//起点
					let origin='';
					if(j==0){ //第一次循环拿司机的地理位置
						origin=longitude+','+latitude;
					}else{ //第二次就正常取上个地理位置
						origin=data[j*num-1].lng+','+data[j*num-1].lat;
					}

					//终点
					let listGus=data.slice(j*num,(j+1)*num)
					let	itemData=listGus.pop();
					let destination=itemData.lng+','+itemData.lat;
					
					//沿途
					let waypoints=[];
					listGus.forEach((it)=>{
						waypoints.push(it.lng+','+it.lat)
					})

					this.getDrivingParametersFun(this.listData.slice(j*num,(j+1)*num),origin,destination,waypoints.join(';'),numNuber);
				}
				if(remainder>0){ //其他剩下的次数
					let listGus=data.slice(group*num,(group+1)*num);
					
					//起点
					let origin='';
					origin=data[group*num-1].lng+','+data[group*num-1].lat;
					
					//终点
					let	itemData=listGus.pop();
					let destination=itemData.lng+','+itemData.lat;
					
					//沿途
					let waypoints=[];
					listGus.forEach((it)=>{
						waypoints.push(it.lng+','+it.lat)
					})

					this.getDrivingParametersFun(this.listData.slice(group*num,(group+1)*num),origin,destination,waypoints.join(';'),numNuber);
				}
			}
		},
		
		//多路径规划
		async getDrivingParametersFun(listData,origin,destination,waypoints,numNuber){
			await getDrivingParameters({
				key:'19ea5029790e6e711275866d839a9c4c',
				origin:origin,
				destination:destination,
				waypoints:waypoints
			})
			.then((res)=>{
				let pathsData=res.route.paths[0];
				console.log(res.route.paths[0],'总数据')
				
				let shijian=0;
				let juli=0;
				let pathIndex=0;//几个途经点
				let points=[]; //途径坐标
				pathsData.steps.forEach((it)=>{
					shijian+=Number.parseInt(it.duration);
					juli+=Number.parseInt(it.distance);
					
					//途径坐标点
					it.polyline.split(';').forEach((itm)=>{
						points.push({
							longitude:itm.split(',')[0],
							latitude:itm.split(',')[1],
						})
					})
					
					if(it.instruction.indexOf("到达途经地") != -1){
						//每次间隔单数都加2分钟
						if(pathIndex!=0)shijian+=this.groupShijian;
						this.listDataFun(listData[pathIndex].id,pathIndex,shijian,juli,points);
						pathIndex+=1;
						points=[]; //重新初始化
						// console.log(pathIndex,'第几个')
						// console.log(shijian,'时间间隔')
						// console.log(juli,'距离间隔')
						shijian=0;
						juli=0;
					}
					
				})
				this.listDataFun(listData[pathIndex].id,pathIndex,shijian,juli,points);
				pathIndex+=1;
				// console.log(pathIndex,'第几个')
				// console.log(shijian,'总时间')
				// console.log(juli,'总距离1')
				
				this.groupIndex+=1;
				if(this.groupIndex==numNuber){
					//多路径规划最终计算距离和时间
					this.listMultipleData();
				}
				
			})
			.finally(()=>{
				// this.loadingTrue=false;
			})
		},
		
		//多路径规划最终计算距离和时间
		listMultipleData(){
			let shijian=0;
			let juli=0;
			this.listData.forEach((item)=>{
				shijian+=Number.parseInt(item.maps_shijian);
				juli+=Number.parseInt(item.maps_juli);
				item.maps_shijian=shijian;
				item.maps_juli=juli;
			})
			console.log(this.listData,'最终')
			// this.loadingTrue=false;
			
			// #ifdef APP-PLUS
			if(this.tabCurrent==0 && this.waypointsBloot){
				this.waypointsBloot=false;
				this.postLogisticAliveFun(false,false);
			}
			// #endif
		},
		
		//多路径导入数据
		listDataFun(id,num,shijian,juli,points){
			let numData=this.listData.findIndex((its)=>its.id==id);
			this.listData[numData].maps_shijian=shijian;
			this.listData[numData].maps_juli=juli;
			this.listData[numData].maps_points=points;
		},
		
		//单路径导入数据
		listDatasFun(listData,num,shijian,juli,points){
			listData[num].maps_shijian=shijian;
			listData[num].maps_juli=juli;
			listData[num].maps_points=points;
		},
		
		//单路径规划
		async getDrivingParametersFunOne(listData,origin,destination,waypoints){
			await getDrivingParameters({
				key:'19ea5029790e6e711275866d839a9c4c',
				origin:origin,
				destination:destination,
				waypoints:waypoints
			})
			.then((res)=>{
				let pathsData=res.route.paths[0];
				// console.log(res.route.paths[0],'总数据')
				
				let shijian=0;
				let juli=0;
				let pathIndex=0;//几个途经点
				let points=[]; //途径坐标
				pathsData.steps.forEach((it)=>{
					shijian+=Number.parseInt(it.duration);
					juli+=Number.parseInt(it.distance);
					
					//途径坐标点
					it.polyline.split(';').forEach((itm)=>{
						points.push({
							longitude:itm.split(',')[0],
							latitude:itm.split(',')[1],
						})
					})
					
					if(it.instruction.indexOf("到达途经地") != -1){
						//每次间隔单数都加2分钟
						if(pathIndex!=0)shijian+=this.groupShijian;
						this.listDatasFun(listData,pathIndex,shijian,juli,points);
						pathIndex+=1;
						points=[]; //重新初始化
						// console.log(pathIndex,'第几个')
						// console.log(shijian,'时间间隔')
						// console.log(juli,'距离间隔')
						
					}
					
				})
				this.listDatasFun(listData,pathIndex,shijian,juli,points);
				pathIndex+=1;
				// console.log(pathIndex,'第几个')
				// console.log(shijian,'总时间')
				// console.log(juli,'总距离1')
				
				
				// #ifdef APP-PLUS
				if(this.tabCurrent==0 && this.waypointsBloot){
					this.waypointsBloot=false;
					this.postLogisticAliveFun(false,false);
				}
				// #endif
				
				console.log(this.listBuData,'this.listBuDatathis.listBuDatathis.listBuData')
			})
			.finally(()=>{
				// this.loadingTrue=false;
			})
		},
		
		//时间戳转换日期
		timestampToTime(timestamp,type=0) {
		  var date = new Date(timestamp);
		  var Y = date.getFullYear() + "";
		  var M =
		    (date.getMonth() + 1 < 10
		      ? "0" + (date.getMonth() + 1)
		      : date.getMonth() + 1) + "";
		  var D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + "";
			if(type==0){
				return Y + M+ D;
			}else{
				return Y+'年'+ M+'月'+ D+'日';
			}	  
		},
		
		//图片上传
		 imgFun(id,type){ //type 1门脸照  2送货图片
			uni.chooseImage({
				count: 1,
				sizeType:['compressed'],
				sourceType: ['camera'],
				success: (res) => {
					this.loadingTrue=true;
					const tempFilePaths = res.tempFilePaths;
					let size = res.tempFiles[0].size; //上传图片大小
					let maxSize = 1024 * 1024 * 10; //最大可上传2mb
					if (size < maxSize) {
						 this.uploadTheImg(tempFilePaths[0],id,type);
					} else {
						uni.showModal({ title: '', showCancel: false, content: '单张图片不能超过10M大小' })
					}		
				}
			})
		},
		
		//图片上传解析
		async uploadTheImg(imgs,id,type){
			await postUploadAlone({
				imgs:imgs,
				save_dir:'/logistic_img'
			})
			.then((res)=>{
				if(type==1){//门脸照
					this.postOrderStoreImageFun(res.url,id);
				}else if(type==2){
					this.postOrderLogisticFun(res.url,id);
				}
				 
			})
			.catch((res)=>{
				this.loadingTrue=false;
				uni.showToast({
						title:'上传失败',
						icon:'none',
						duration: 2000
				});	
			})
		},
		
		//司机门脸照postOrderLogistic
		async postOrderStoreImageFun(imgs,id){
			await postOrderStoreImage({
				logistic_id:id,
				image:imgs
			})
			.then((res)=>{
				this.listData[this.listData.findIndex((value) => value.id == id)].logistic_face=res.image;
			})
			.catch((res)=>{
				console.log(res,'失败')
				uni.showToast({
						title:'上传失败',
						icon:'none',
						duration: 2000
				});	
			})
			.finally(()=>{
				this.loadingTrue=false;
			})
		},
		
		//送货图片
		async postOrderLogisticFun(imgs,id){
			let arrs=[];
			let nums=this.listData.findIndex((value) => value.id == id);
			console.log(this.listData[nums],'this.listData[nums]')
			if(this.listData[nums].images.length>0){
				arrs=this.listData[nums].images;
				arrs.push(imgs);
			}else{
				arrs.push(imgs);
			}
			await postOrderLogistic({
				logistic_id:id,
				images:arrs
			})
			.then((res)=>{
				this.listData[nums].images=res.images;
			})
			.catch((res)=>{
				console.log(res,'失败')
				uni.showToast({
						title:'上传失败',
						icon:'none',
						duration: 2000
				});	
			})
			.finally(()=>{
				this.loadingTrue=false;
			})
		},
		
		//物流单修改状态
		async postOrderLogisticStatus(logistic_id,status,bloos=false){
			//0待配送 1 完成 2 送货中
			if(status==0)console.log('物流单状态:待配送')
			if(status==0 && bloos){
				this.listData=this.listStatusData;
			}
			
			if(status==2)console.log('物流单状态:送货中')
			if(status==0 || status==2){
				this.listData[this.listData.findIndex((value) => value.id == logistic_id)].status=status;
				this.listData[this.listData.findIndex((value) => value.id == logistic_id)].status_show=(status==2?'送货中':'待配送');
				console.log(this.listData[this.listData.findIndex((value) => value.id == logistic_id)].status,'状态是多少')
			}
			if(status==1){
				console.log('物流单状态:完成');
				this.showOne=false;
				this.loadingTrue=true;
			}
			if(status==2){ //判断如果等于2，送货列表排序到第一个
				//保存数据
				this.listStatusData=JSON.parse(JSON.stringify(this.listData));
			
				//排序到第一个列表
				let datas=this.listData.splice(this.listData.findIndex((value) => value.id == logistic_id), 1);
				this.listData.unshift(datas[0]);
			}
			await postOrderLogistic({
				logistic_id,status
			})
			.then((res)=>{
				if(status==1){
					this.loadingType = 0;
					this.addressFun();
				}
				
				// #ifdef APP-PLUS
				if(this.tabCurrent==0){
					// this.postLogisticAliveFun(false,false);
					this.addressStatusFun();
				}
				// #endif
			})
			.finally(()=>{
				this.loadingTrue=false;
			})
		},
		
		//获取经纬度
		addressStatusFun(){
			// #ifdef APP-PLUS
			let _this=this;
			uni.getLocation({
					type: 'gcj02',
					isHighAccuracy:true,
					success: function (res) {
						console.log(res,'坐标')
						_this.waypointsBloot=true;
						_this.waypointsFun(res.longitude,res.latitude);
					},
					fail: error => {
						
					}
			});	
			// #endif
			// #ifdef H5
			// this.postOrderListFun(29.62388,106.583256); //我家
			this.postOrderListFun(29.623894,106.583275); //公司1
			// #endif
		},
		
		space(lat1, lng1, lat2, lng2) {
			console.log(lat1, lng1, lat2, lng2)
			var radLat1 = lat1 * Math.PI / 180.0;
			var radLat2 = lat2 * Math.PI / 180.0;
			var a = radLat1 - radLat2;
			var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
			var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
					 Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
			s = s * 6378.137;
			s = Math.round(s * 10000) / 10000;
			return s  // 单位千米
		},

		
		//获取定位async
		 async postLogisticAliveFun(data,type=true){
			// console.log(data,'定位1')
			let sjData=null;
			let customizeData={
				listTrue:this.customize,
				dateTime:Date.now()
			}
			let items=this.is_same_day(this.dateValue); //时间是同一天吗
			console.log(items,'----时间是同一天吗-----');
	
			if(this.customize && this.tabCurrent==0 && items){
				if(type){
					sjData={
						data:JSON.stringify(this.listData),
						location:JSON.stringify(data),
						customize:JSON.stringify(customizeData)		
					}
					console.log('全传')
					//更新预计时间和沿途坐标点
					this.waypointsFun(data.longitude,data.latitude);
				}else{
					sjData={
						data:JSON.stringify(this.listData),
						customize:JSON.stringify(customizeData)		
					}
					console.log('不传经纬度')
				}
			}else{
				sjData={
					location:JSON.stringify(data),
					customize:JSON.stringify(customizeData)		
				}
				console.log('不传列表1')
			}
			
			await postLogisticAlive(sjData)
			.then((res)=>{
				// console.log(123)
			})
		},
		
		is_same_day(t){
			return new Date(t).toDateString() === new Date().toDateString();
		}
		
		
	}
})
 
//暴露用户小仓库
export default useCustomerStore